package com.snail.config;

import cn.dev33.satoken.stp.StpUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author 蔡徐坤
 * @Date 2025/8/13 19:23
 * @Description: 把前端带过来的 token 放到 header 中，以便后续的鉴权
 */
@Component
public class SaTokenGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String tokenName = StpUtil.getTokenName();

        String tokenValue = exchange.getRequest().getHeaders().getFirst(tokenName);
        // 如果前端带过来了 token，则放到 header 中
        if (tokenValue != null) {
            exchange = exchange.mutate().request(
                    exchange.getRequest().mutate().header(tokenName, tokenValue).build()
            ).build();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }

}
